package com.rent.core.interceptor;

import com.rent.common.utils.StringUtils;
import com.security.config.IgnoreUrlsConfig;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author zhang
 * @create 2021/7/10 14:40
 */
@Slf4j
@Component
public class MyInterceptor implements HandlerInterceptor {

    private static final String AUTHORIZE_TOKEN = "Authorization";

    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        String url = request.getRequestURI();
        log.info("请求拦截:" + url);
        //白名单请求直接放行
        PathMatcher pathMatcher = new AntPathMatcher();
        for (String path : ignoreUrlsConfig.getUrls()) {
            if (pathMatcher.match(path, url)) {
                return true;
            }
        }
        String token = request.getHeader(AUTHORIZE_TOKEN);
//        log.info("请求的token:{}", token);
        return !StringUtils.isEmpty(token);
    }
}
